<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>病历管理</title>
    <link rel="stylesheet" href="css/adminMedicalRecordList.css">
    <script src="js/jquery.min.js"></script>
</head>
<body>
<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
            <li><a href="./adminUserList.html">用户管理</a></li>
            <li><a href="./adminMedicalRecordList.html" class="active">病历管理</a></li>
            <li><a href="./adminPersonalCenter.html">个人信息管理</a></li>
            <li><a href="./adminMedicalTemplate.html">病历模板管理</a></li>
            <li><a href="./adminUpdateRequest.html">信息修改申请</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="info-card">
            <h2>病历列表</h2>

            <!-- 搜索和筛选 -->
            <div class="search-input-container">
                <input type="text" id="medicalRecordSearchInput" class="search-input" placeholder="输入诊断结果搜索">
            </div>

            <!-- 添加病历按钮 -->
            <div class="button-container">
                <button class="btn btn-success" id="addMedicalRecordBtn">新增病历</button>
            </div>

            <!-- 病历列表表格 -->
            <table class="medical-records-table">
                <thead>
                    <tr>
                        <th>病历ID</th>
                        <th>挂号ID</th>
                        <th>患者姓名</th>
                        <th>医生姓名</th>
                        <th>挂号时间</th>
                        <th>主诉</th>
                        <th>诊断结果</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="medicalRecordTableBody">
                    <!-- 病历数据将在这里加载 -->
                </tbody>
            </table>

            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将在这里加载 -->
                </ul>
            </nav>

            <div id="loading" class="loading-message" style="display: none;">加载中...</div>
            <div id="error" class="error-message" style="display: none;">加载失败</div>
        </div>
    </div>
</div>

<!-- 新增病历模态框 -->
<div id="addMedicalRecordModal" class="modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addMedicalRecordModalLabel">新增病历</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addMedicalRecordForm">
                    <div class="form-group">
                        <label for="addRegisterId" class="form-label">挂号记录</label>
                        <select class="form-control" id="addRegisterId" required>
                            <option value="">请选择挂号记录</option>
                            <%-- 挂号记录选项将在这里加载 --%>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="templateSelect" class="form-label">选择病历模板</label>
                        <select class="form-control" id="templateSelect">
                            <option value="">请选择病历模板 (可选)</option>
                            <%-- 病历模板选项将在这里加载 --%>
                        </select>
                    </div>
                    <div class="form-group full-width">
                        <label for="addReadme" class="form-label">主诉</label>
                        <textarea class="form-control" id="addReadme" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addPresent" class="form-label">现病史</label>
                        <textarea class="form-control" id="addPresent" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addPresentTreat" class="form-label">现病治疗情况</label>
                        <textarea class="form-control" id="addPresentTreat" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addHistory" class="form-label">既往史</label>
                        <textarea class="form-control" id="addHistory" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addAllergy" class="form-label">过敏史</label>
                        <textarea class="form-control" id="addAllergy" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addPhysique" class="form-label">体格检查</label>
                        <textarea class="form-control" id="addPhysique" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addProposal" class="form-label">检查/检验建议</label>
                        <textarea class="form-control" id="addProposal" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addCareful" class="form-label">注意事项</label>
                        <textarea class="form-control" id="addCareful" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addDiagnosis" class="form-label">诊断结果</label>
                        <textarea class="form-control" id="addDiagnosis" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="addCure" class="form-label">处理意见</label>
                        <textarea class="form-control" id="addCure" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveMedicalRecordBtn">保存病历</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑病历模态框 -->
<div id="editMedicalRecordModal" class="modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editMedicalRecordModalLabel">编辑病历</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editMedicalRecordForm">
                    <input type="hidden" id="editMedicalRecordId"> <!-- 隐藏字段存放病历ID -->
                    <div class="form-group full-width">
                        <label for="editRegisterIdDisplay" class="form-label">挂号记录</label>
                        <span id="editRegisterIdDisplay" class="form-control-plaintext"></span> <!-- 显示挂号记录信息，不可编辑 -->
                    </div>
                    <!-- 以下字段与新增病历模态框中的字段类似，用于编辑 -->
                    <div class="form-group full-width">
                        <label for="editReadme" class="form-label">主诉</label>
                        <textarea class="form-control" id="editReadme" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editPresent" class="form-label">现病史</label>
                        <textarea class="form-control" id="editPresent" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editPresentTreat" class="form-label">现病治疗情况</label>
                        <textarea class="form-control" id="editPresentTreat" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editHistory" class="form-label">既往史</label>
                        <textarea class="form-control" id="editHistory" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editAllergy" class="form-label">过敏史</label>
                        <textarea class="form-control" id="editAllergy" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editPhysique" class="form-label">体格检查</label>
                        <textarea class="form-control" id="editPhysique" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editProposal" class="form-label">检查/检验建议</label>
                        <textarea class="form-control" id="editProposal" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editCareful" class="form-label">注意事项</label>
                        <textarea class="form-control" id="editCareful" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editDiagnosis" class="form-label">诊断结果</label>
                        <textarea class="form-control" id="editDiagnosis" rows="3"></textarea>
                    </div>
                    <div class="form-group full-width">
                        <label for="editCure" class="form-label">处理意见</label>
                        <textarea class="form-control" id="editCure" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditMedicalRecordBtn">保存修改</button>
            </div>
        </div>
    </div>
</div>

<script>
$(function(){
    let currentPage = 1;
    const pageSize = 10;
    const backendBaseUrl = 'http://localhost:8080';

    // 显示模态框
    function showModal(modalId) {
        const $modal = $('#' + modalId);
        $modal.css('display', 'block').addClass('show');

        // 点击背景关闭模态框
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('modal')) {
                hideModal(modalId);
            }
        });

        // 关闭按钮事件
        $modal.find('.close, .btn-secondary').on('click', function() {
            hideModal(modalId);
        });
    }

    // 隐藏模态框
    function hideModal(modalId) {
        const $modal = $('#' + modalId);
        $modal.css('display', 'none').removeClass('show');
        $modal.off('click');
        $modal.find('.close, .btn-secondary').off('click');
    }

    // 获取病历列表数据
    function loadMedicalRecords() {
        $('#loading').show();
        $('#error').hide();
        const keyword = $('#medicalRecordSearchInput').val();

        $.ajax({
            url: backendBaseUrl + '/medical/admin/list',
            type: 'GET',
            data: {
                pageNum: currentPage,
                pageSize: pageSize,
                keyword: keyword
            },
            xhrFields: { withCredentials: true }, // 确保携带 cookie
            success: function(res){
                $('#loading').hide();
                if(res.code === 0 && res.data){
                    const pageData = res.data;
                    const medicalRecords = pageData.records;
                    const total = pageData.total;

                    const $tbody = $('#medicalRecordTableBody');
                    $tbody.empty();

                    if (medicalRecords.length === 0) {
                        $tbody.append('<tr><td colspan="8" class="text-center">无病历数据</td></tr>');
                        $('#pagination').empty(); // 清空分页
                        return;
                    }

                    medicalRecords.forEach(record => {
                        const $row = $('<tr>');
                        $row.append($('<td>').text(record.id));
                        $row.append($('<td>').text(record.registerId));
                        $row.append($('<td>').text(record.patientUsername || '-'));
                        $row.append($('<td>').text(record.doctorUsername || '-'));
                        $row.append($('<td>').text(record.registerTime ? new Date(record.registerTime).toLocaleString() : '-'));
                        $row.append($('<td>').text(record.readme || '-'));
                        $row.append($('<td>').text(record.diagnosis || '-'));

                        const $deleteButton = $('<button>').addClass('btn btn-danger delete-btn').text('删除').attr('data-id', record.id);
                        const $editButton = $('<button>').addClass('btn btn-primary edit-btn').text('编辑').attr('data-id', record.id);

                        const $actionsCell = $('<td>').append($editButton).append($deleteButton);
                        $row.append($actionsCell);

                        $tbody.append($row); // 添加行到表格体
                    });

                    // 更新分页控件
                    updatePagination(total);
                    $('#pagination').data('total-records', total); // 存储总记录数供分页点击使用

                } else {
                    $('#error').text(res.message || '获取病历列表失败').show();
                    $('#pagination').empty();
                }
            },
            error: function(){
                $('#loading').hide();
                $('#error').text('请求失败，请稍后重试').show();
                $('#pagination').empty();
            }
        });
    }

     // 更新分页控件
    function updatePagination(total) {
        const $pagination = $('#pagination');
        $pagination.empty();
        const totalPages = Math.ceil(total / pageSize);

        if (totalPages <= 1) {
            return; // 少于等于1页不显示分页
        }

        // 添加首页和上一页按钮
        $pagination.append(createPaginationItem(1, '首页', currentPage === 1));
        $pagination.append(createPaginationItem(currentPage - 1, '上一页', currentPage === 1));

        // 添加页码
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
            $pagination.append(createPaginationItem(1, 1));
            if (startPage > 2) {
                $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            $pagination.append(createPaginationItem(i, i, i === currentPage));
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
            }
            $pagination.append(createPaginationItem(totalPages, totalPages));
        }

        // 添加下一页和尾页按钮
        $pagination.append(createPaginationItem(currentPage + 1, '下一页', currentPage === totalPages));
        $pagination.append(createPaginationItem(totalPages, '尾页', currentPage === totalPages));
    }

    // 辅助函数：创建分页链接项
    function createPaginationItem(page, text, isDisabled = false) {
            const $li = $('<li>').addClass('page-item');
        if (isDisabled) {
            $li.addClass('disabled');
        }
        if (page === currentPage && !isDisabled) {
                $li.addClass('active');
            }
        const $link = $('<a>').addClass('page-link').attr('href', '#').text(text).attr('data-page', page);
            $li.append($link);
        return $li;
    }

    // 删除病历
    function deleteMedicalRecord(recordId) {
        if (confirm('确定要删除此病历吗？')) {
            $.ajax({
                url: backendBaseUrl + '/medical/admin/' + recordId,
                type: 'DELETE',
                xhrFields: { withCredentials: true },
                success: function(res){
                    if(res.code === 0){
                        alert('病历删除成功');
                        loadMedicalRecords();
                    } else {
                        alert(res.message || '删除失败');
                    }
                },
                error: function(){
                    alert('删除失败，请稍后重试');
                }
            });
        }
    }

    // 使用事件委托为动态添加的删除按钮绑定点击事件
    $('#medicalRecordTableBody').on('click', '.delete-btn', function(){
        const recordId = $(this).data('id');
        deleteMedicalRecord(recordId);
    });

    // 搜索框输入事件
    $('#medicalRecordSearchInput').on('input', function(){
        currentPage = 1;
        loadMedicalRecords();
    });

    // 分页点击事件 (事件委托)
    $('#pagination').on('click', '.page-link', function(e){
        e.preventDefault();
        const page = $(this).data('page');
        const $parentLi = $(this).parent('li');
        const total = $('#pagination').data('total-records'); // 需要在更新分页时存储总记录数

        if ($parentLi.hasClass('disabled') || $parentLi.hasClass('active')) {
            return;
        }

        if (page >= 1 && page <= Math.ceil(total / pageSize)) {
             currentPage = parseInt(page);
             loadMedicalRecords();
        }
    });

    // 显示新增病历模态框按钮点击事件
    $('#addMedicalRecordBtn').click(function(){
        $('#addMedicalRecordForm')[0].reset(); // 重置表单
        loadRegistersForSelect(); // 加载挂号记录
        loadMedicalTemplatesForSelect(); // 加载病历模板
        showModal('addMedicalRecordModal');
    });

    // 保存新增病历按钮点击事件
    $('#saveMedicalRecordBtn').click(function(){
        const medicalRecordData = {
            registerId: $('#addRegisterId').val(),
            readme: $('#addReadme').val(),
            present: $('#addPresent').val(),
            presentTreat: $('#addPresentTreat').val(),
            history: $('#addHistory').val(),
            allergy: $('#addAllergy').val(),
            physique: $('#addPhysique').val(),
            proposal: $('#addProposal').val(),
            careful: $('#addCareful').val(),
            diagnosis: $('#addDiagnosis').val(),
            cure: $('#addCure').val()
        };

        $.ajax({
            url: backendBaseUrl + '/medical/admin/add',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(medicalRecordData),
            xhrFields: { withCredentials: true },
            success: function(res){
                if(res.code === 0){
                    alert('病历添加成功');
                    hideModal('addMedicalRecordModal');
                    loadMedicalRecords();
                } else {
                    alert(res.message || '病历添加失败');
                }
            },
            error: function(){
                alert('病历添加失败，请稍后重试');
            }
        });
    });

    // 加载挂号记录并填充下拉框 (新增模态框)
    function loadRegistersForSelect() {
        $.ajax({
            url: backendBaseUrl + '/admin/register/listForMedicalRecord',
            type: 'GET',
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const $select = $('#addRegisterId');
                    $select.empty();
                    $select.append($('<option>').val('').text('请选择挂号记录'));
                    res.data.forEach(register => {
                        const optionText = '挂号ID: ' + register.id + ' - 患者: ' + (register.patientUsername || '-') + ' - 医生: ' + (register.doctorUsername || '-');
                        $select.append($('<option>').val(register.id).text(optionText));
                    });
                } else {
                    console.error('获取挂号记录失败:', res.message);
                }
            },
            error: function() {
                console.error('获取挂号记录失败');
            }
        });
    }

    // 加载病历模板并填充下拉框 (新增模态框)
    function loadMedicalTemplatesForSelect() {
        $.ajax({
            url: backendBaseUrl + '/admin/medical/templates/list',
            type: 'GET',
             xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const $select = $('#templateSelect');
                    $select.empty();
                    $select.append($('<option>').val('').text('请选择病历模板 (可选)'));
                    res.data.forEach(template => {
                        $select.append($('<option>').val(template.id).text(template.name));
                    });
                } else {
                    console.error('获取病历模板失败:', res.message);
                }
            },
            error: function() {
                console.error('获取病历模板失败');
            }
        });
    }

    // 根据模板ID获取模板内容并填充表单 (新增模态框)
    $('#templateSelect').on('change', function(){
        const selectedTemplateId = $(this).val();
        if (!selectedTemplateId) {
            // 如果选择了"请选择模板"，则清空表单内容（挂号记录除外）
            $('#addMedicalRecordForm')[0].reset();
             // 保留挂号记录的选中值
            const currentRegisterId = $('#addRegisterId').val();
            loadRegistersForSelect(); // 重新加载挂号记录，以便能够重新设置选中值
            $('#addRegisterId').val(currentRegisterId); // 尝试恢复之前选中的挂号记录
            return;
        }
        $.ajax({
            url: backendBaseUrl + '/admin/medical/templates/' + selectedTemplateId,
            type: 'GET',
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0 && res.data) {
                    try {
                        const templateContent = JSON.parse(res.data.content);
                        $('#addReadme').val(templateContent.readme || '');
                        $('#addPresent').val(templateContent.present || '');
                        $('#addPresentTreat').val(templateContent.present_treat || '');
                        $('#addHistory').val(templateContent.history || '');
                        $('#addAllergy').val(templateContent.allergy || '');
                        $('#addPhysique').val(templateContent.physique || '');
                        $('#addProposal').val(templateContent.proposal || '');
                        $('#addCareful').val(templateContent.careful || '');
                        $('#addDiagnosis').val(templateContent.diagnosis || '');
                        $('#addCure').val(templateContent.cure || '');
                    } catch (e) {
                        console.error('解析模板内容失败:', e);
                        alert('加载模板内容失败，模板内容格式不正确。');
                    }
                } else {
                    console.error('获取模板详情失败:', res.message);
                    alert('获取模板详情失败。');
                }
            },
            error: function() {
                console.error('获取模板详情失败');
                alert('获取模板详情失败，请稍后重试。');
            }
        });
    });

    // 监听编辑按钮点击事件 (事件委托)
    $('#medicalRecordTableBody').on('click', '.edit-btn', function(){
        const recordId = $(this).data('id');
        if (recordId) {
            loadMedicalRecordForEdit(recordId);
            showModal('editMedicalRecordModal');
        }
    });

    // 加载病历详情并填充编辑模态框
    function loadMedicalRecordForEdit(recordId) {
        $('#editMedicalRecordForm')[0].reset(); // 重置表单
        $.ajax({
            url: backendBaseUrl + '/medical/admin/' + recordId,
            type: 'GET',
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const record = res.data;
                    $('#editMedicalRecordId').val(record.id);
                    $('#editRegisterIdDisplay').text('挂号ID: ' + record.registerId + ' - 患者: ' + (record.patientUsername || '-') + ' - 医生: ' + (record.doctorUsername || '-')); // 显示挂号记录信息
                    $('#editReadme').val(record.readme || '');
                    $('#editPresent').val(record.present || '');
                    $('#editPresentTreat').val(record.presentTreat || '');
                    $('#editHistory').val(record.history || '');
                    $('#editAllergy').val(record.allergy || '');
                    $('#editPhysique').val(record.physique || '');
                    $('#editProposal').val(record.proposal || '');
                    $('#editCareful').val(record.careful || '');
                    $('#editDiagnosis').val(record.diagnosis || '');
                    $('#editCure').val(record.cure || '');
                } else {
                    alert('获取病历详情失败: ' + (res.message || ''));
                }
            },
            error: function() {
                alert('获取病历详情失败，请稍后重试。');
            }
        });
    }

    // 保存编辑后的病历
    $('#saveEditMedicalRecordBtn').click(function(){
        const medicalRecordData = {
            id: $('#editMedicalRecordId').val(),
            // 挂号ID在编辑时不可修改
            readme: $('#editReadme').val(),
            present: $('#editPresent').val(),
            presentTreat: $('#editPresentTreat').val(),
            history: $('#editHistory').val(),
            allergy: $('#editAllergy').val(),
            physique: $('#editPhysique').val(),
            proposal: $('#editProposal').val(),
            careful: $('#editCareful').val(),
            diagnosis: $('#editDiagnosis').val(),
            cure: $('#editCure').val()
        };

        $.ajax({
            url: backendBaseUrl + '/medical/admin/update',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(medicalRecordData),
            xhrFields: { withCredentials: true },
            success: function(res){
                if(res.code === 0){
                    alert('病历修改成功');
                    hideModal('editMedicalRecordModal');
                    loadMedicalRecords();
                } else {
                    alert(res.message || '病历修改失败');
                }
            },
            error: function(){
                alert('病历修改失败，请稍后重试');
            }
        });
    });

    // 页面加载时获取病历列表
    loadMedicalRecords();

});
</script>
</body>
</html> 